<?php
declare (strict_types = 1);

namespace app\model\communal;

use think\db\Query;
use think\Model;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

/**
 * Class app\model\communal\UserCoinModel
 */
class UserCoinModel extends Model
{
    /**
     * 数据库配置
     *
     * @var string
     */
    protected $connection = 'communal';

    /**
     * 主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $table = '55700_user_coin';

    /**
     * 自动时间戳
     *
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间字段设置
     *
     * @var string
     */
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 软删除
     */
    use SoftDelete;
    protected $deleteTime = 'delete_at';
    protected $defaultSoftDelete = 0;

    /**
     * 展示字段名
     *
     * @var string[]
     */
    public static $column = ['user_id', 'coin_count', 'coin_balance', 'remark', 'type', 'created_at'];

    /**
     * 搜索字段名
     *
     * @var string[]
     */
    public static $searchColumn = [
        'id', 'user_id', 'type',
    ];

    /**
     * 新增字段
     *
     * @var string[]
     */
    public static $saveColumn = ['user_id', 'coin_count', 'coin_balance', 'remark', 'type', ];

    /**
     * user_id 搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchUserIdAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('user_id', $value);
        }
    }

    /**
     * 关联用户
     *
     * @return BelongsTo
     */
    public function belongUser()
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id')
            ->removeOption('soft_delete')
            ->bind([
                'user_name' => 'name',
                'user_avatar' => 'avatar',
                'user_mobile' => 'mobile'
            ]);
    }
}
